<template>
  <div class="monitor-dashboard">
    <!-- 动态科技背景 -->
    <div class="cyber-background">
      <div class="grid-overlay"></div>
      <div class="particle-field"></div>
      <div class="data-stream"></div>
    </div>

    <!-- 全息投影式头部 -->
    <header class="holographic-header">
      <div class="header-content">
        <div class="logo-container">
          <div class="logo-hologram">
            <div class="logo-core"></div>
            <div class="logo-ring"></div>
            <div class="logo-particles"></div>
          </div>
          <h1 class="system-title">API MONITOR SYSTEM</h1>
        </div>

        <!-- 添加标语容器 -->
        <div class="slogan-container">
          <div class="typing-effect">
            <div class="typing-text" :class="{ 'shatter': isShatterActive }">
              {{ currentText }}
            </div>
            <div class="text-particles" v-if="isShatterActive">
              <span 
                v-for="(particle, index) in textParticles" 
                :key="index"
                class="particle"
                :style="particle.style"
              >{{ particle.char }}</span>
            </div>
          </div>
        </div>

        <div class="system-status">
          <div class="status-ring">
            <svg viewBox="0 0 100 100">
              <circle class="status-circle" cx="50" cy="50" r="45"/>
            </svg>
            <div class="status-time">{{ currentTime }}</div>
          </div>
          <div class="status-text">
            系统运行中 | 检测模式: {{ currentMode }}
          </div>
        </div>
      </div>
    </header>

    <!-- 主控制面板 -->
    <main class="control-panel">
      <!-- 状态概览卡片 -->
      <section class="status-overview">
        <div class="metric-card" v-for="metric in systemMetrics" :key="metric.id">
          <div class="metric-icon" :class="metric.trend">
            <i :class="metric.icon"></i>
          </div>
          <div class="metric-data">
            <div class="metric-value">{{ metric.value }}</div>
            <div class="metric-label">{{ metric.label }}</div>
          </div>
        </div>
      </section>

      <!-- API状态监控网格 -->
      <section class="monitor-grid">
        <div class="grid-header">
          <h2 class="neo-title">API 实时状态控</h2>
          <div class="view-controls">
            <button 
              v-for="view in viewModes" 
              :key="view.id"
              :class="['view-btn', { active: currentView === view.id }]"
              @click="setView(view.id)"
            >
              <i :class="view.icon"></i>
            </button>
          </div>
        </div>

        <transition-group 
          name="grid-transition" 
          tag="div" 
          class="api-container"
          :class="currentView"
        >
          <div 
            v-for="api in apis" 
            :key="api.id"
            class="api-node"
            :class="[getStatusClass(api.status), { 'pulse': api.loading }]"
          >
            <div class="node-header">
              <div class="status-indicator">
                <div class="pulse-ring"></div>
                <div class="status-core"></div>
              </div>
              <span class="api-type">{{ api.apiapply }}</span>
            </div>

            <div class="node-content">
              <h3 class="api-name">{{ api.name }}</h3>
              <div class="api-metrics">
                <div class="metric">
                  <i class="fas fa-tachometer-alt"></i>
                  <span>{{ api.loading ? '检测中...' : `${api.speed || '0'}ms` }}</span>
                </div>
                <div class="metric">
                  <i class="fas fa-clock"></i>
                  <span>{{ api.lastCheck }}</span>
                </div>
              </div>
            </div>

            <div class="node-footer">
              <div class="status-text" :class="getStatusClass(api.status)">
                {{ getStatusText(api.status) }}
              </div>
              <a :href="api.apiurl" class="api-link" target="_blank">
                <i class="fas fa-external-link-alt"></i>
              </a>
            </div>

            <!-- 悬浮详情 -->
            <div class="node-details">
              <div class="detail-item">
                <span class="label">请求总数</span>
                <span class="value">{{ api.requestCount }}</span>
              </div>
              <div class="detail-item">
                <span class="label">平均响应</span>
                <span class="value">{{ api.avgResponse }}ms</span>
              </div>
              <div class="detail-item">
                <span class="label">成功率</span>
                <span class="value">{{ api.successRate }}%</span>
              </div>
            </div>
          </div>
        </transition-group>
      </section>
    </main>

    <!-- 系统告警面板 -->
    <div class="alert-panel" :class="{ 'show': hasAlerts }">
      <div class="alert-header">
        <i class="fas fa-exclamation-triangle"></i>
        <span>系统告警</span>
      </div>
      <div class="alert-content">
        <div 
          v-for="alert in activeAlerts" 
          :key="alert.id"
          class="alert-item"
          :class="alert.severity"
        >
          <div class="alert-icon">
            <i :class="getAlertIcon(alert.type)"></i>
          </div>
          <div class="alert-info">
            <div class="alert-title">{{ alert.title }}</div>
            <div class="alert-message">{{ alert.message }}</div>
            <div class="alert-time">{{ formatTime(alert.time) }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted } from 'vue';
import axios from 'axios';

export default {
  name: 'WatchApi',

  setup() {
    // 状态变量
    const currentTime = ref('');
    const currentMode = ref('全时段监控');
    const currentView = ref('grid');
    const apis = ref([]);
    const hasAlerts = ref(false);
    const activeAlerts = ref([]);

    // 系统指标数据
    const systemMetrics = ref([
      {
        id: 1,
        label: 'API总数',
        value: '32',
        icon: 'fas fa-layer-group',
        trend: 'up'
      },
      {
        id: 2,
        label: '在线接口',
        value: '28',
        icon: 'fas fa-check-circle',
        trend: 'stable'
      },
      {
        id: 3,
        label: '平均响应时间',
        value: '126ms',
        icon: 'fas fa-tachometer-alt',
        trend: 'down'
      },
      {
        id: 4,
        label: '今日调用次数',
        value: '1,234',
        icon: 'fas fa-exchange-alt',
        trend: 'up'
      }
    ]);

    // 视图模式
    const viewModes = [
      { id: 'grid', icon: 'fas fa-th' },
      { id: 'list', icon: 'fas fa-list' },
      { id: 'map', icon: 'fas fa-project-diagram' }
    ];

    // 导航项
    const navItems = [
      { id: 1, label: '控制台', icon: 'fas fa-home', action: () => {} },
      { id: 2, label: '配置', icon: 'fas fa-cog', action: () => {} },
      { id: 3, label: '报告', icon: 'fas fa-chart-bar', action: () => {} }
    ];

    // 添加打字动画相关的状态
    const currentText = ref('');
    const isShatterActive = ref(false);
    const textParticles = ref([]);
    const slogans = [
      "「 实时监控，智能预警 」",
      "「 全方位API健康检测 」",
      "「 数据驱动，稳定可靠 」",
      "「 高效运维，极致体验 」",
      "「 智能分析，洞察先机 」"
    ];
    let currentIndex = 0;
    let charIndex = 0;

    // 方法定义
    const fetchApiStatus = async () => {
      try {
        const response = await axios.get('/api/apiList');
        if (response.data.code === 200) {
          apis.value = response.data.data;
          checkApiStatus();
        }
      } catch (error) {
        console.error('获取API状态失败:', error);
      }
    };

    const checkApiStatus = () => {
      apis.value.forEach(async (api) => {
        api.loading = true;
        try {
          const response = await axios.get(`/api/check-url?url=${encodeURIComponent(api.apiurl)}`);
          api.loading = false;
          api.speed = response.data.latency;
          api.status = response.data.code === 200;
        } catch (error) {
          api.loading = false;
          api.status = false;
          api.speed = 0;
        }
      });
    };

    const updateTime = () => {
      const now = new Date();
      currentTime.value = now.toLocaleTimeString();
    };

    const getStatusClass = (status) => {
      return status ? 'status-normal' : 'status-error';
    };

    const getStatusText = (status) => {
      return status ? '正常运行' : '服务异常';
    };

    const setView = (viewId) => {
      currentView.value = viewId;
    };

    const getAlertIcon = (type) => {
      const icons = {
        error: 'fas fa-times-circle',
        warning: 'fas fa-exclamation-triangle',
        info: 'fas fa-info-circle'
      };
      return icons[type] || icons.info;
    };

    const formatTime = (time) => {
      return new Date(time).toLocaleString();
    };

    // 打字效果函数
    const typeText = async () => {
      const slogan = slogans[currentIndex];
      if (charIndex < slogan.length) {
        currentText.value = slogan.substring(0, charIndex + 1);
        charIndex++;
        const delay = Math.random() * 50 + 100; // 100-150ms的随机延迟
        setTimeout(typeText, delay);
      } else {
        await new Promise(resolve => setTimeout(resolve, 2000));
        shatterText();
      }
    };

    // 碎片化动画函数
    const shatterText = () => {
      const text = slogans[currentIndex];
      textParticles.value = [];
      
      for (let i = 0; i < text.length; i++) {
        const char = text[i];
        const angle = Math.random() * 360;
        const velocity = 2 + Math.random() * 3;
        const tx = Math.cos(angle) * velocity * 100;
        const ty = Math.sin(angle) * velocity * 100;
        const rot = (Math.random() - 0.5) * 720;

        textParticles.value.push({
          char,
          style: {
            '--tx': `${tx}px`,
            '--ty': `${ty}px`,
            '--rot': `${rot}deg`,
            left: `${(i / text.length) * 100}%`,
            top: '50%',
            transform: 'translate(-50%, -50%)'
          }
        });
      }

      isShatterActive.value = true;

      setTimeout(() => {
        isShatterActive.value = false;
        textParticles.value = [];
        currentIndex = (currentIndex + 1) % slogans.length;
        charIndex = 0;
        currentText.value = '';
        typeText();
      }, 1000);
    };

    // 生命周期钩子
    onMounted(() => {
      document.title = 'E特尔诺-API监控中心';
      fetchApiStatus();
      updateTime();
      const timeInterval = setInterval(updateTime, 1000);
      const statusInterval = setInterval(checkApiStatus, 30000);
      
      // 启动打字动画
      typeText();

      onUnmounted(() => {
        clearInterval(timeInterval);
        clearInterval(statusInterval);
        // 重置动画状态
        charIndex = 0;
        currentIndex = 0;
        isShatterActive.value = false;
        textParticles.value = [];
      });
    });

    return {
      currentTime,
      currentMode,
      currentView,
      apis,
      systemMetrics,
      viewModes,
      navItems,
      hasAlerts,
      activeAlerts,
      getStatusClass,
      getStatusText,
      setView,
      getAlertIcon,
      formatTime,
      currentText,
      isShatterActive,
      textParticles
    };
  }
};
</script>

<style scoped>
/* 基础样式与动画 */
.monitor-dashboard {
  min-height: 100vh;
  background: #0a0b1e;
  color: #fff;
  overflow: hidden;
  position: relative;
}

/* 动态背景效果 */
.cyber-background {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
}

.grid-overlay {
  position: absolute;
  width: 200%;
  height: 200%;
  top: -50%;
  left: -50%;
  background-image: 
    linear-gradient(rgba(32, 202, 255, 0.05) 1px, transparent 1px),
    linear-gradient(90deg, rgba(32, 202, 255, 0.05) 1px, transparent 1px);
  background-size: 50px 50px;
  animation: gridMove 20s linear infinite;
  transform-origin: center;
}

.particle-field {
  position: absolute;
  width: 100%;
  height: 100%;
  background: radial-gradient(circle at center, rgba(32, 202, 255, 0.1) 0%, transparent 50%);
  filter: blur(20px);
  animation: pulse 4s ease-in-out infinite;
}

.data-stream {
  position: absolute;
  width: 100%;
  height: 100%;
  background: 
    linear-gradient(90deg, 
      transparent 0%,
      rgba(32, 202, 255, 0.05) 15%,
      rgba(32, 202, 255, 0.1) 50%,
      rgba(32, 202, 255, 0.05) 85%,
      transparent 100%);
  transform: skewX(-45deg);
  animation: dataFlow 8s linear infinite;
}

/* 全息投影头部 */
.holographic-header {
  position: relative;
  padding: 2rem;
  z-index: 1;
  background: rgba(10, 11, 30, 0.8);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(32, 202, 255, 0.2);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  max-width: 1400px;
  margin: 0 auto;
  padding: 1rem;
  gap: 2rem;
}

.logo-container {
  display: flex;
  align-items: center;
  gap: 1.5rem;
}

.logo-hologram {
  position: relative;
  width: 60px;
  height: 60px;
}

.logo-core {
  position: absolute;
  width: 30px;
  height: 30px;
  background: rgba(32, 202, 255, 0.8);
  border-radius: 50%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  box-shadow: 0 0 20px rgba(32, 202, 255, 0.5);
  animation: corePulse 2s ease-in-out infinite;
}

.logo-ring {
  position: absolute;
  width: 100%;
  height: 100%;
  border: 2px solid rgba(32, 202, 255, 0.3);
  border-radius: 50%;
  animation: ringRotate 4s linear infinite;
}

.logo-particles {
  position: absolute;
  width: 100%;
  height: 100%;
  background: radial-gradient(circle at center, rgba(32, 202, 255, 0.8) 0%, transparent 70%);
  filter: blur(5px);
  animation: particlesFloat 3s ease-in-out infinite;
}

.system-title {
  font-size: 2rem;
  font-weight: 700;
  background: linear-gradient(45deg, #fff, #20caff);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  text-shadow: 0 0 10px rgba(32, 202, 255, 0.3);
}

/* 系统状态显示 */
.system-status {
  display: flex;
  align-items: center;
  gap: 2rem;
}

.status-ring {
  position: relative;
  width: 80px;
  height: 80px;
}

.status-circle {
  fill: none;
  stroke: #20caff;
  stroke-width: 2;
  stroke-dasharray: 283;
  stroke-dashoffset: 0;
  animation: circleRotate 2s linear infinite;
}

.status-time {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 0.9rem;
  font-weight: 500;
  color: #20caff;
}

/* 量子导航 */
.quantum-nav {
  display: flex;
  justify-content: center;
  gap: 2rem;
  margin-top: 2rem;
}

.nav-item {
  position: relative;
  padding: 1rem 2rem;
  cursor: pointer;
  transition: all 0.3s ease;
}

.nav-icon {
  font-size: 1.5rem;
  margin-bottom: 0.5rem;
  color: #20caff;
}

.nav-label {
  font-size: 0.9rem;
  font-weight: 500;
}

.quantum-highlight {
  position: absolute;
  bottom: -2px;
  left: 50%;
  width: 0;
  height: 2px;
  background: #20caff;
  transform: translateX(-50%);
  transition: width 0.3s ease;
}

.nav-item:hover .quantum-highlight {
  width: 100%;
}

/* 控制面板 */
.control-panel {
  max-width: 1400px;
  margin: 2rem auto;
  padding: 0 2rem;
  position: relative;
  z-index: 1;
}

/* 状态概览卡片 */
.status-overview {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 1.5rem;
  margin-bottom: 3rem;
}

.metric-card {
  background: rgba(255, 255, 255, 0.03);
  border: 1px solid rgba(32, 202, 255, 0.2);
  border-radius: 16px;
  padding: 1.5rem;
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
}

.metric-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(32, 202, 255, 0.1);
  border-color: rgba(32, 202, 255, 0.4);
}

.metric-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  background: rgba(32, 202, 255, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.5rem;
  color: #20caff;
  margin-bottom: 1rem;
}

.metric-value {
  font-size: 2rem;
  font-weight: 700;
  color: #fff;
  margin-bottom: 0.5rem;
}

.metric-label {
  font-size: 0.9rem;
  color: rgba(255, 255, 255, 0.7);
}

/* API监控网格 */
.monitor-grid {
  background: rgba(255, 255, 255, 0.02);
  border-radius: 20px;
  padding: 2rem;
  border: 1px solid rgba(32, 202, 255, 0.1);
}

.grid-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
}

.neo-title {
  font-size: 1.5rem;
  font-weight: 600;
  color: #fff;
  display: flex;
  align-items: center;
  gap: 1rem;
}

.neo-title::before {
  content: '';
  width: 4px;
  height: 24px;
  background: #20caff;
  border-radius: 2px;
}

.view-controls {
  display: flex;
  gap: 1rem;
}

.view-btn {
  background: none;
  border: 1px solid rgba(32, 202, 255, 0.3);
  color: rgba(255, 255, 255, 0.7);
  padding: 0.5rem 1rem;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.view-btn.active {
  background: rgba(32, 202, 255, 0.1);
  border-color: #20caff;
  color: #20caff;
}

/* API节点卡片 */
.api-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 1.5rem;
}

.api-node {
  background: rgba(255, 255, 255, 0.03);
  border: 1px solid rgba(32, 202, 255, 0.2);
  border-radius: 16px;
  padding: 1.5rem;
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
}

.api-node:hover {
  transform: translateY(-5px);
  border-color: #20caff;
  box-shadow: 0 10px 20px rgba(32, 202, 255, 0.1);
}

.node-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
}

.status-indicator {
  position: relative;
  width: 40px;
  height: 40px;
}

.pulse-ring {
  position: absolute;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  animation: pulseRing 2s ease-out infinite;
}

.status-core {
  position: absolute;
  width: 12px;
  height: 12px;
  background: #20caff;
  border-radius: 50%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.api-type {
  font-size: 0.9rem;
  color: rgba(255, 255, 255, 0.7);
  padding: 0.25rem 0.75rem;
  background: rgba(32, 202, 255, 0.1);
  border-radius: 20px;
}

.node-content {
  margin-bottom: 1.5rem;
}

.api-name {
  font-size: 1.2rem;
  font-weight: 600;
  color: #fff;
  margin-bottom: 1rem;
}

.api-metrics {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
}

.metric {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  color: rgba(255, 255, 255, 0.7);
  font-size: 0.9rem;
}

.node-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.status-text {
  padding: 0.25rem 0.75rem;
  border-radius: 20px;
  font-size: 0.9rem;
  font-weight: 500;
}

.api-link {
  color: #20caff;
  transition: all 0.3s ease;
}

.api-link:hover {
  transform: scale(1.1);
}

/* 状态样式 */
.status-normal .pulse-ring {
  border: 2px solid rgba(76, 175, 80, 0.5);
}

.status-normal .status-core {
  background: #4caf50;
}

.status-error .pulse-ring {
  border: 2px solid rgba(244, 67, 54, 0.5);
}

.status-error .status-core {
  background: #f44336;
}

/* 动画定义 */
@keyframes gridMove {
  0% {
    transform: translate(0, 0) rotate(0deg);
  }
  100% {
    transform: translate(-50px, -50px) rotate(3deg);
  }
}

@keyframes pulse {
  0%, 100% {
    opacity: 0.5;
    transform: scale(1);
  }
  50% {
    opacity: 1;
    transform: scale(1.2);
  }
}

@keyframes dataFlow {
  0% {
    transform: translateX(-100%) skewX(-45deg);
  }
  100% {
    transform: translateX(100%) skewX(-45deg);
  }
}

@keyframes corePulse {
  0%, 100% {
    transform: translate(-50%, -50%) scale(1);
    opacity: 1;
  }
  50% {
    transform: translate(-50%, -50%) scale(1.2);
    opacity: 0.8;
  }
}

@keyframes ringRotate {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

@keyframes particlesFloat {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-10px);
  }
}

@keyframes circleRotate {
  0% {
    stroke-dashoffset: 0;
  }
  100% {
    stroke-dashoffset: 283;
  }
}

@keyframes pulseRing {
  0% {
    transform: scale(0.7);
    opacity: 1;
  }
  100% {
    transform: scale(1.5);
    opacity: 0;
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 2rem;
  }

  .quantum-nav {
    flex-wrap: wrap;
  }

  .control-panel {
    padding: 0 1rem;
  }

  .status-overview {
    grid-template-columns: 1fr;
  }

  .api-container {
    grid-template-columns: 1fr;
  }
}

/* 标语容器样式 */
.slogan-container {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60px;
  overflow: hidden;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 12px;
  padding: 0 1rem;
  backdrop-filter: blur(5px);
}

.typing-effect {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  perspective: 1000px;
}

.typing-text {
  font-size: 1.5rem;
  font-weight: 700;
  color: #20caff;
  text-shadow: 0 0 10px rgba(32, 202, 255, 0.5);
  white-space: nowrap;
  position: relative;
  transform-style: preserve-3d;
  transition: all 0.3s ease;
  letter-spacing: 2px;
  text-align: center;
}

.typing-text.shatter {
  opacity: 0;
  transform: scale(1.2) rotate(5deg);
}

.text-particles {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.particle {
  position: absolute;
  color: #20caff;
  font-weight: 700;
  font-size: 2rem;
  text-shadow: 0 0 10px rgba(32, 202, 255, 0.5);
  pointer-events: none;
  animation: particleFade 1s ease-out forwards;
}

/* 打字光标效果 */
.typing-text::after {
  content: '|';
  animation: cursor 1s infinite step-start;
  margin-left: 2px;
}

@keyframes cursor {
  50% { opacity: 0; }
}

@keyframes particleFade {
  0% {
    opacity: 1;
    transform: translate(0, 0) rotate(0deg);
  }
  100% {
    opacity: 0;
    transform: translate(var(--tx), var(--ty)) rotate(var(--rot));
  }
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .header-content {
    flex-direction: column;
    gap: 1rem;
  }

  .slogan-container {
    width: 100%;
  }

  .typing-text {
    font-size: 1.2rem;
  }
}
</style>